#Get objects
old_ws = ls()

#############
#Tables NVMS#
#############

useTable_nvms = mergedTable_nvms_placebo[!is.na(NVM_Violence_1_count) & (sample_ni_it)]

#################
#Events Analysis#
#################

#Model specifications
nb_specs = expand.grid(x = 'IT_win', y = c('NVM_Violence_1_count', 'NVM_Violence_1_deaths'), stringsAsFactors = F)
lm_specs = expand.grid(x = 'IT_win', y = c('NVM_Violence_1_binary', 'NVM_Violence_1_deaths_binary'), stringsAsFactors = F)

#Estimate models
nvms_nb_models = Map(function(y,x) glmnb_loop(y,x, useTable_nvms),
                     nb_specs$y, nb_specs$x)

nvms_lm_models = Map(function(y,x) lm_loop(y,x,  useTable_nvms),
                     lm_specs$y, lm_specs$x)

nvms_list = c(nvms_nb_models, nvms_lm_models)
nvms_se = lapply(nvms_list, function(x) cluster_errors(x, useTable_nvms[, cluster]) %>% diag %>% sqrt)

table_list = c(nvms_list)
table_se = c(nvms_se)

#create table
n_clusters = useTable_nvms[, cluster] %>% unique %>% length

note_text = paste("Count models use negative binomial regression; binary outcomes use OLS. Standard errors are clustered by constituency-clusters. In the NVMS  there are ", n_clusters, " clusters. Observations are constituencies in which the last seat was contested by Islamist and secular nationalist parties with a margin less than 1 percent.")

table = stargazer(table_list, se = table_se, type = 'latex', 
                  title = "Estimated Effects of Islamist Victory on Religious Violence: NVMS (Placebo)",
                  label = 'tab:placebo_nvms_violence_ni_it',
                  model.names = F,
                  model.numbers = T,
                  column.separate = c(4),
                  column.labels = c('NVMS'),
                  multicolumn = T,
                  dep.var.labels = rep(c("Events","Deaths"), 2), 
                  add.lines = list(c('Count', rep(c('Y', 'Y', 'N', 'N'), 1)),
                                   c('Binary', rep(c('N', 'N', 'Y', 'Y'), 1))),
                  covariate.labels = c("Islamist Win"),
                  star.cutoffs = c(0.1, 0.05, 0.01),
                  #float.env = 'sidewaystable',
                  notes.align = 'l',
                  font.size = 'scriptsize',
                  keep.stat = 'n',
                  style = 'apsr')



write_latex(table[-10] %>% append(table[10], after = 10) %>% append("\\cmidrule(lr){2-5}", after = 10), note_text, './output/tables/table_d2.tex')

#Clean up
drop = setdiff(ls(), c(old_ws)) 
rm(list = drop)

